package com.yami.shop.service.impl;


import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.event.ProdDetailEvent;
import com.yami.shop.bean.model.SingleChoiceQue;
import com.yami.shop.bean.model.VrScene;
import com.yami.shop.bean.model.VrSceneDetail;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.dao.VrSceneMapper;
import com.yami.shop.service.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author SJL
 * @date 2021-02-20 09:44:42
 */
@Service
@AllArgsConstructor
public class VrSceneServiceImpl extends ServiceImpl<VrSceneMapper, VrScene> implements VrSceneService {
    @Autowired
    private VrSceneDetailService vrSceneDetailService;
    @Autowired
    private VrSceneMapper vrSceneMapper;
    @Autowired
    private SingleChoiceQueService singleChoiceQueService;
    @Autowired
    private ApplicationContext applicationContext;

    private final SysConfigService sysConfigService;
    private final AttachFileService attachFileService;
    @Override
    public void saveVrScene(VrScene vrScene) {
        this.save(vrScene);
        List<VrSceneDetail> vrSceneDetailList = vrScene.getVrSceneDetailList();
        for (VrSceneDetail vrSceneDetail:vrSceneDetailList) {
            vrSceneDetail.setSceneId(vrScene.getId());
            vrSceneDetail.setCreateTime(new Date());
        }
        vrSceneDetailService.saveBatch(vrSceneDetailList);
        createQrcode(vrScene.getId());
    }
    private void createQrcode(Long id) {
        QrConfig config = new QrConfig(300,300);
        BufferedImage qrgenerate = QrCodeUtil.generate(sysConfigService.getValue("VRSCENE_URL")+"/#/?id="+id, config);
        //保存图片
        ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
        //读文件
        try {
            ImageIO.write(qrgenerate,"jpg",qrOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile ossMultipartFile = new OssMultipartFile("222.jpg", ".jpg", qrOutputStream.toByteArray());
        try {
            String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID()+".jpg");
            // 获取微发行链接地址
            sysConfigService.getValue("VRSCENE_URL");
            // 保存链接信息
            UpdateWrapper<VrScene> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",id);
            updateWrapper.set("qrcode_addr",fileName);
            this.update(updateWrapper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void updateVrScene(VrScene vrScene) {
        vrScene.setUpdateTime(new Date());
        this.updateById(vrScene);
        List<VrSceneDetail> vrSceneDetailList = vrScene.getVrSceneDetailList();
        if(vrSceneDetailList.size()>0){
            List<Long> newAll = vrSceneDetailList.stream().filter(s->s.getSceneDetailId()!=null).map(s -> s.getSceneDetailId()).collect(Collectors.toList());
            List<VrSceneDetail> list = vrSceneDetailService.list(new LambdaQueryWrapper<VrSceneDetail>().eq(VrSceneDetail::getSceneId, vrScene.getId()).eq(VrSceneDetail::getStatus, "0").select(VrSceneDetail::getSceneDetailId));
            List<Long> oldAll = list.stream().map(s -> s.getSceneDetailId()).collect(Collectors.toList());
            List<VrSceneDetail> insertAll = new ArrayList<>();
            List<VrSceneDetail> updateAll = new ArrayList<>();
            oldAll.removeAll(newAll);
            for (VrSceneDetail vrSceneDetail:vrSceneDetailList) {
                if(vrSceneDetail.getSceneDetailId()==null){
                    vrSceneDetail.setSceneId(vrScene.getId());
                    vrSceneDetail.setCreateTime(new Date());
                    insertAll.add(vrSceneDetail);
                }else{
                    vrSceneDetail.setUpdateTime(new Date());
                    updateAll.add(vrSceneDetail);
                }
            }
            if(insertAll.size()>0){
                vrSceneDetailService.saveBatch(insertAll);
            }
            if(updateAll.size()>0){
                vrSceneDetailService.updateBatchById(updateAll);
            }
            if(oldAll.size()>0){
                LambdaUpdateWrapper<VrSceneDetail> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.in(VrSceneDetail::getSceneDetailId,oldAll);
                lambdaUpdateWrapper.set(VrSceneDetail::getStatus,"1");
                lambdaUpdateWrapper.set(VrSceneDetail::getUpdateTime,new Date());
                vrSceneDetailService.update(lambdaUpdateWrapper);
            }
        }else{
            LambdaUpdateWrapper<VrSceneDetail> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(VrSceneDetail::getSceneId,vrScene.getId());
            lambdaUpdateWrapper.set(VrSceneDetail::getStatus,"1");
            lambdaUpdateWrapper.set(VrSceneDetail::getUpdateTime,new Date());
            vrSceneDetailService.update(lambdaUpdateWrapper);
        }
    }

    @Override
    public VrScene getInfoById(Long id) {
        VrScene infoById = vrSceneMapper.getInfoById(id);
        // 获取 绑定权益商品信息
        for(VrSceneDetail vrSceneDetail : infoById.getVrSceneDetailList()){
            ProdDetailEvent prodDetailEvent = new ProdDetailEvent();
            prodDetailEvent.setVrSceneDetail(vrSceneDetail);
            applicationContext.publishEvent(prodDetailEvent);
        }
        // 如果是 灯谜类型 获取 灯谜信息
        if(infoById.getSceneType().equals("2")){
            SingleChoiceQue singleChoiceQue = singleChoiceQueService.getQueDetail(infoById.getQueIds());
            infoById.setSingleChoiceQue(singleChoiceQue);
        }
        return infoById;
    }

    @Override
    public void removeVrSceneById(Long id) {
        VrScene vrScene = new VrScene();
        vrScene.setUpdateTime(new Date());
        vrScene.setId(id);
        vrScene.setStatus("2");
        this.updateById(vrScene);
        LambdaUpdateWrapper<VrSceneDetail> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(VrSceneDetail::getSceneId,id);
        lambdaUpdateWrapper.set(VrSceneDetail::getStatus,"1");
        lambdaUpdateWrapper.set(VrSceneDetail::getCreateTime,new Date());
        vrSceneDetailService.update(lambdaUpdateWrapper);
    }
}
